<template>
	<div class="group-store">
    <div class="table-title">
      <el-button type="primary" @click="handleAdd" data-auth="bloc_store_add">添加门店</el-button>
    </div>
    <div class="table-content">
      <el-table
        border
        :data="tableData"
        style="width: 100%">
        <el-table-column
          label="门店名称"
          prop="Name">
        </el-table-column>
        <el-table-column
          label="门店类型"
					prop="HotelTypeStr">
        </el-table-column>
        <el-table-column
          label="门店电话"
          prop="Phone">
        </el-table-column>
        <el-table-column
          label="门店所在城市"
          prop="CityName">
        </el-table-column>
        <el-table-column
          label="门店具体地址"
          prop="FullAddress">
        </el-table-column>
        <el-table-column
          label="短信项目标识">
					<template slot-scope="scope">{{scope.row.SMSSign}}</template>
        </el-table-column>
        <el-table-column label="操作" width="315px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)" data-auth="bloc_store_modify">修改门店信息</el-button>
            <el-button
              size="mini"
              @click="handleColAdd(scope.$index, scope.row)" data-auth="bloc_store_detail">完善外显信息</el-button>
            <el-button
              size="mini"
              type="primary"
							v-if="!scope.row.IsOnLine"
              @click="handleOnline(scope.$index, scope.row)" data-auth="bloc_store_putaway">上架</el-button>
						<el-button
							size="mini"
							v-if="scope.row.IsOnLine"
							@click="handleOffline(scope.$index, scope.row)" data-auth="bloc_store_putaway">下架</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="table-page">
			<el-pagination
			  background
				@size-change="changePage"
      	@current-change="getList"
      	:current-page.sync="searchData.pageIndex"
      	:page-sizes="[100, 200, 300, 400]"
			  layout="total,prev, pager, next"
			  :total="pageTotal">
			</el-pagination>
    </div>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="roomShow"
      width="600px"
      center>
      <el-form :model="addData" :rules="rules" ref="ruleForm" label-width="120px">
        <el-form-item label="门店名称：" prop="Name">
          <el-input v-model="addData.Name"></el-input>
        </el-form-item>
        <el-form-item label="门店类型：" prop="HotelType">
          <el-radio v-model="addData.HotelType" :label="5001" border>客栈</el-radio>
          <el-radio v-model="addData.HotelType" :label="5002" border>酒店</el-radio>
          <el-radio v-model="addData.HotelType" :label="5003" border>公寓</el-radio>
        </el-form-item>
        <el-form-item label="联系电话：" prop="Phone">
          <el-input v-model="addData.Phone"></el-input>
        </el-form-item>
				<div class="cityDiv">
					<el-form-item label="所在城市：" prop="ProvinceId">
	          <el-select v-model="addData.ProvinceId" placeholder="请选择所在省" @change="querylistbypid(addData.ProvinceId,'CityList','addData','CityId')">
							<el-option
							 v-for="item in ProvinceList"
							 :key="item.Id"
							 :label="item.CnName"
							 :value="item.Id">
						 </el-option>
	          </el-select>
	        </el-form-item>
					<el-form-item prop="CityId" label-width="0px">
						<el-select v-model="addData.CityId" placeholder="请选择所在市" @change="querylistbypid(addData.CityId,'AreaList','addData','ZoneId')">
							<el-option
							 v-for="item in CityList"
							 :key="item.Id"
							 :label="item.CnName"
							 :value="item.Id">
						 </el-option>
						</el-select>
					</el-form-item>
					<el-form-item label-width="0px" prop="ZoneId">
						<el-select v-model="addData.ZoneId" placeholder="请选择所在区">
							<el-option
							 v-for="item in AreaList"
							 :key="item.Id"
							 :label="item.CnName"
							 :value="item.Id">
						 </el-option>
						</el-select>
					</el-form-item>
				</div>
				<el-form-item label="短信项目标识" prop="SMSSign">
					<el-input v-model="addData.SMSSign"></el-input>
				</el-form-item>
        <el-form-item label=" 具体地址：" prop="FullAddress">
          <el-input v-model="addData.FullAddress"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="btnSave('ruleForm')">{{dialogTitle==='添加门店'?'确认添加':'确认修改'}}</el-button>
        <el-button @click="roomShow = false">取 消</el-button>
      </span>
    </el-dialog>


    <el-dialog
      :title="dialogTitle"
      :visible.sync="roomColShow"
			class="twocol-dialog"
      width="800px"
      center>
      <el-form :model="colForm" :rules="colrules" ref="colForm" label-width="130px">
        <el-form-item label="酒店名称：" class="fifty" prop="Name">
          <el-input v-model="colForm.Name"></el-input>
        </el-form-item>
        <el-form-item label="酒店外显名称：" class="fifty" prop="ExternalName">
          <el-input v-model="colForm.ExternalName"></el-input>
        </el-form-item>
        <el-form-item label="酒店类型：" class="fifty" prop="HotelType">
          <el-select v-model="colForm.HotelType" placeholder="请选择酒店类型">
						<el-option label="民宿" :value="5001"></el-option>
						<el-option label="酒店" :value="5002"></el-option>
            <el-option label="公寓" :value="5003"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label=" 酒店简介：" class="fifty" prop="Describe">
          <el-input v-model="colForm.Describe"></el-input>
        </el-form-item>
				<div class="cityDiv">
					<el-form-item label="所在城市：" prop="ProvinceId">
	          <el-select v-model="colForm.ProvinceId" placeholder="请选择所在省" @change="querylistbypid(colForm.ProvinceId,'CityList','colForm','CityId')">
							<el-option
							 v-for="item in ProvinceList"
							 :key="item.Id"
							 :label="item.CnName"
							 :value="item.Id">
						 </el-option>
	          </el-select>
	        </el-form-item>
					<el-form-item prop="CityId" label-width="0px">
						<el-select v-model="colForm.CityId" placeholder="请选择所在市" @change="querylistbypid(colForm.CityId,'AreaList','colForm','ZoneId')">
							<el-option
							 v-for="item in CityList"
							 :key="item.Id"
							 :label="item.CnName"
							 :value="item.Id">
						 </el-option>
						</el-select>
					</el-form-item>
					<el-form-item label-width="0px" prop="ZoneId">
						<el-select v-model="colForm.ZoneId" placeholder="请选择所在区">
							<el-option
							 v-for="item in AreaList"
							 :key="item.Id"
							 :label="item.CnName"
							 :value="item.Id">
						 </el-option>
						</el-select>
					</el-form-item>
				</div>
        <el-form-item label="具体地址：" prop="FullAddress">
          <el-input v-model="colForm.FullAddress"></el-input>
        </el-form-item>
        <el-form-item label=" 经度：" class="fifty" prop="Longitude">
          <el-input v-model="colForm.Longitude"></el-input>
        </el-form-item>
        <el-form-item label=" 纬度：" class="fifty" prop="Latitude">
          <el-input v-model="colForm.Latitude"></el-input>
        </el-form-item>
        <el-form-item label=" 联系电话：" class="fifty" prop="Phone">
          <el-input v-model="colForm.Phone"></el-input>
        </el-form-item>
        <el-form-item label=" 客房总数：" class="fifty" prop="TotalRoom">
          <el-input v-model="colForm.TotalRoom"></el-input>
        </el-form-item>
        <el-form-item label=" 开业时间：" class="fifty" prop="OpeningDate">
					<el-date-picker
			      v-model="colForm.OpeningDate"
			      type="date"
			      placeholder="选择日期"
			      format="yyyy 年 MM 月 dd 日"
			      value-format="yyyy-MM-dd"
						:editable="false"
						:clearable="false">
			    </el-date-picker>
        </el-form-item>
        <el-form-item label=" 装修时间：" class="fifty" prop="RenovationDate">
					<el-date-picker
			      v-model="colForm.RenovationDate"
			      type="date"
			      placeholder="选择日期"
			      format="yyyy 年 MM 月 dd 日"
			      value-format="yyyy-MM-dd"
						:editable="false"
						:clearable="false">
			    </el-date-picker>
        </el-form-item>
        <el-form-item label="酒店图片：" prop="ImageList">
					<el-upload
            class="avatar-uploader"
            action="/"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            >
            <el-button type="primary">点击上传图片</el-button>
          </el-upload>
          <div class="el-upload__tip">请上传png、jpg及jpeg格式图片(大小2M以下,建议分辨率256*256)</div>
          <span class="upload-imglist" v-for="(m,index) in colForm.ImageList">
            <el-checkbox v-model="m.IsMasterPhoto" label="设置为封面图" @change="setIsMasterPhoto(m)"></el-checkbox>
            <img v-if="colForm.ImageList.length>0" :src="m.Url">
            <i class="el-icon-circle-close-outline" @click="colForm.ImageList.splice(index,1)"></i>
          </span>
        </el-form-item>
        <el-form-item label="入住提示：">
					<el-checkbox-group v-model="checkHotelHits">
	            <el-checkbox :label="n.ItemCode" v-for="n in hotelHits" :key="n.Id">{{n.ItemName}}</el-checkbox>
	        </el-checkbox-group>
        </el-form-item>
        <el-form-item label=" 酒店设施服务：" prop="HotelFacilitiesList">
					<span class="si-span" v-for="(m,index) in colForm.HotelFacilitiesList">
						<el-select class="s-select" v-model="m.FacilityType" placeholder="请选择">
	            <el-option label="网络" :value="1"></el-option>
	            <el-option label="交通设施" :value="2"></el-option>
	            <el-option label="交通服务" :value="3"></el-option>
	            <el-option label="儿童设施" :value="4"></el-option>
	            <el-option label="休闲娱乐" :value="5"></el-option>
	            <el-option label="前台服务" :value="6"></el-option>
	            <el-option label="餐饮服务" :value="7"></el-option>
	            <el-option label="商务服务" :value="8"></el-option>
	            <el-option label="其他服务" :value="9"></el-option>
	          </el-select>
	          <el-input class="s-input" v-model="m.FacilityValue"></el-input>
						<i class="el-icon-plus" @click="colForm.HotelFacilitiesList.push({FacilityType:'',FacilityValue:''})"></i>
						<i class="el-icon-minus" v-if="index!==0" @click="()=>{colForm.HotelFacilitiesList.splice(index,1);$refs['colForm'].validateField('HotelFacilitiesList')}"></i>
					</span>
        </el-form-item>
        <el-form-item label=" 酒店周边设施：" prop="HotelSurroundFacilitiesList">
					<span class="si-span" v-for="(m,index) in colForm.HotelSurroundFacilitiesList">
	          <el-select class="s-select" v-model="m.FacilityType" placeholder="请选择">
	            <el-option label="餐饮" :value="1"></el-option>
	            <el-option label="购物" :value="2"></el-option>
	            <el-option label="娱乐" :value="3"></el-option>
	            <el-option label="景点" :value="4"></el-option>
	            <el-option label="交通" :value="5"></el-option>
	          </el-select>
	          <el-input class="s-input" v-model="m.FacilityValue"></el-input>
						<i class="el-icon-plus" @click="colForm.HotelSurroundFacilitiesList.push({FacilityType:'',FacilityValue:''})"></i>
						<i class="el-icon-minus" v-if="index!==0" @click="()=>{colForm.HotelSurroundFacilitiesList.splice(index,1);$refs['colForm'].validateField('HotelSurroundFacilitiesList')}"></i>
					</span>
        </el-form-item>
        <el-form-item label=" 酒店政策：" prop="HotelPolicies">
          <el-input v-model="colForm.HotelPolicies.CheckInOutDesc" class="w30"><template slot="prepend">入离时间</template></el-input>
          <el-input v-model="colForm.HotelPolicies.ChildPolicy" class="w30"><template slot="prepend">儿童政策</template></el-input>
          <el-input v-model="colForm.HotelPolicies.PetPolicy" class="w30"><template slot="prepend">宠物政策</template></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveColForm('colForm')">保存</el-button>
        <el-button @click="roomColShow = false">取 消</el-button>
      </span>
    </el-dialog>
	</div>
</template>
<script>
	  export default {
        data () {
					const _this=this;
            return {
							checkHotelHits:[],
							hotelHits:[],
							ProvinceList:[],
							CityList:[],
							AreaList:[],
							pageTotal:0,
              dialogTitle:'',
              roomShow:false,
              dialogColTitle:'',
              roomColShow:false,
							searchData:{
								Id:JSON.parse(sessionStorage.getItem('nowmenu')).Id,
								pageIndex:1,
								pageSize:10
							},
              fileList: [],
              tableData: [],
              addData: {
								Name:'',
								HotelType:5001,
							 	Phone:'',
								ProvinceId:'',
								CityId:'',
								ZoneId: '',
								Type:3,
								FullAddress:'',
								SMSSign:''
              },
              colForm: {
								hotelHits:[],
								"Longitude": "",
							  "Latitude": "",
							  "OpeningDate": "",
							  "RenovationDate": "",
							  "Describe": "",
							  "TotalRoom": "",
							  "ImageList": [],
							  "HotelFacilitiesList": [
							    {
							      "FacilityType": "",
							      "FacilityValue": ""
							    }
							  ],
							  "HotelSurroundFacilitiesList": [
							    {
							      "FacilityType": "",
							      "FacilityValue": ""
							    }
							  ],
							  "HotelPolicies": {
							    "CheckInOutDesc": "",
							    "ChildPolicy": "",
							    "PetPolicy": ""
							  },
							  "Name": "",
							  "BlocId": JSON.parse(sessionStorage.getItem('nowmenu')).Id,
							  "HotelType": "",
							  "ProvinceId": "",
							  "CityId": "",
							  "ZoneId": "",
							  "FullAddress": "",
							  "Phone": "",
              },
              rules: {
                Name: [
                  { required: true, message: '请输入门店名称', trigger: 'blur' },
                ],
                HotelType: [
                  { required: true, message: '请选择门店类型', trigger: 'blur' }
                ],
                Phone: [
                  { required: true, message: '请输入联系电话', trigger: 'blur' },
                ],
                ProvinceId: [
                  { required: true, message: '请选择省份', trigger: 'change' },
                ],
                CityId: [
                  { required: true, message: '请选择城市', trigger: 'change' }
                ],
                ZoneId: [
                  { required: true, message: '请选择区域', trigger: 'change' }
                ],
                FullAddress: [
                  { required: true, message: '请输入具体地址', trigger: 'blur' }
                ],
								SMSSign: [
                  { required: true, message: '请输入短信项目标识', trigger: 'blur' }
                ],
              },
							colrules: {
                Name: [
                  { required: true, message: '请输入酒店名称', trigger: 'blur' },
                ],
								ExternalName: [
                  { required: true, message: '请输入外显名称', trigger: 'blur' },
                ],
                HotelType: [
                  { required: true, message: '请选择酒店类型', trigger: 'change' }
                ],
								ProvinceId: [
									{ required: true, message: '请选择省份', trigger: 'change' },
								],
								CityId: [
									{ required: true, message: '请选择城市', trigger: 'change' }
								],
								ZoneId: [
									{ required: true, message: '请选择区域', trigger: 'change' }
								],
                FullAddress: [
                  { required: true, message: '请输入详细地址', trigger: 'blur' }
                ],
								Longitude: [
                  { required: false, message: '', trigger: 'blur' }
                ],
								Latitude: [
                  { required: false, message: '', trigger: 'blur' }
                ],
								OpeningDate: [
                  { required: true, message: '请选择开业时间', trigger: 'change' }
                ],
							  RenovationDate: [
                 { required: true, message: '请选择装修时间', trigger: 'change' }
                ],
								Phone: [
                  { required: true, message: '请输入联系电话', trigger: 'blur' }
                ],
								TotalRoom: [
                  { required: true, message: '请输入客房总数', trigger: 'blur' }
                ],
								Describe: [
                  { required: true, message: '请输入酒店简介', trigger: 'blur' }
                ],
								hotelHits: [
                  { required: true,type:"array", message: '请选择入住提示', trigger: 'change' }
                ],
								HotelFacilitiesList: [
                  { required: true, validator: (rule, value, callback) => {
                      if (value.some(val=>{return !val.FacilityType})){
												callback(new Error('请选择酒店设施服务'));
											}
											else if(value.some(val=>{return !val.FacilityValue})) {
                        callback(new Error('请输入酒店设施服务'));
                      }
											else if(_this.arrRepeat(value,'FacilityType')){
												callback(new Error('酒店设施类型不得重复'));
											}
											else {
                        callback();
                      }
                    }, trigger: 'change' }
                ],
								HotelSurroundFacilitiesList: [
                  { required: true, validator: (rule, value, callback) => {
                      if (value.some(val=>{return !val.FacilityType})){
												callback(new Error('请选择酒店周边设施'));
											}
											else if(value.some(val=>{return !val.FacilityValue})) {
                        callback(new Error('请输入酒店周边设施'));
                      }
											else if(_this.arrRepeat(value,'FacilityType')){
												callback(new Error('酒店周边设施类型不得重复'));
											}
											else {
                        callback();
                      }
                    }, trigger: 'change' }
                ],
								HotelPolicies: [
                  { required: true, validator: (rule, value, callback) => {
                      if (Object.values(value).some(val=>{return val===""})) {
                        callback(new Error('请输入酒店政策'));
                      } else {
                        callback();
                      }
                    }, trigger: 'change' }
                ],
								ImageList: [
                  { required: true,validator: (rule, value, callback) => {
                      if (!_this.colForm.ImageList.length) {
                        callback(new Error('请上传酒店图片'));
                      } else {
                        callback();
                      }
                    }, trigger: 'focus' }
                ],
              }
						}
        },
        created(){
					this.initList();
					this.querylistbypid(1,'ProvinceList');
					this.$ajax.GetConfigByTypeCode().then(res=>{
						if(res.Success){
							this.hotelHits=res.Data;
						}
					})
        },
        methods:{
					arrRepeat(arr,type){
						arr=arr.reduce((aa,val)=>{
							aa.push(val[type]);
							return aa
						},[]);
						let arrStr = JSON.stringify(arr),str;
						for (let i = 0; i < arr.length; i++) {
							if (arrStr.indexOf(arr[i]) != arrStr.lastIndexOf(arr[i])){
								return true;
							}
						};
						return false;
					},
					querylistbypid(id,type,data,reset){
						if(reset){
							this[data][reset]='';
						}
						this.$ajax.querylistbypid({pid:id}).then(res=>{
							if(res.Success){
								this[type]=res.Data;
							}
						})
					},
					initList(){
						this.searchData.pageIndex=1;
						this.roomShow=false;
						this.roomColShow=false;
						this.getList();
					},
					changePage(size){
						this.searchData.pageIndex=1;
						this.searchData.pageSize=size;
						this.getList();
					},
					getList(){
						this.$ajax.GetHotelInfoByPage(this.searchData).then(res=>{
							if(res.Success){
								this.tableData=res.Data.PagedData;
								this.pageTotal=res.Data.TotalCount;
							}
						})
					},
					beforeAvatarUpload(file) {
		        const isJPG = file.type === 'image/jpeg'||file.type === 'image/png';
		        const isLt2M = file.size / 1024 / 1024 < 2;
		        if (!isJPG) {
		          this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
		          return
		        }
		        if (!isLt2M) {
		          this.$message.error('上传头像图片大小不能超过 2MB!');
		          return
		        }
		        let reader = new FileReader()
		        reader.readAsDataURL(file)
		        reader.onloadend = ()=>{
		          file.url = reader.result;
		          this.$ajax.upLoadImg({FileName:file.name,FileBase64:file.url.split(',')[1]}).then(res=>{
		            if(res.Success){
		                this.colForm.ImageList.push(
		                  {
		                    Name: file.name,
		                    Url: res.Data,
		                    IsMasterPhoto: false
		                  }
		                );
										this.$refs['colForm'].validateField('ImageList');
		            }
		          })
		        }
		        return false;
		      },
          resetForm(formName) {
            if(!this.$refs[formName]){return};
            this.$refs[formName].resetFields();
						console.log(this.addData);
          },
          handleAdd(index, row) {
            this.dialogTitle='添加门店';
						this.addData={
							BlocId:JSON.parse(sessionStorage.getItem('nowmenu')).Id,
							Name:'',
							HotelType:5001,
							Phone:'',
							ProvinceId:'',
							CityId:'',
							Type:3,
							ZoneId: '',
							FullAddress:''
						};
						this.CityList=[];
						this.AreaList=[];
            this.resetForm('ruleForm');
						this.$nextTick(()=>{
							this.roomShow=true;
						})
          },
          handleEdit(index, row) {
            this.dialogTitle='编辑门店';
            this.resetForm('ruleForm');
						this.$ajax.GetBlocInfoById({id:row.Id}).then(res=>{
							if(res.Success){
								this.addData=res.Data;
								this.querylistbypid(this.addData.ProvinceId,'CityList');
								this.querylistbypid(this.addData.CityId,'AreaList');
								this.roomShow=true;
							}
						})
          },
          handleColAdd(index, row) {
						this.dialogTitle='完善外显信息';
            this.resetForm('colForm');
						this.$ajax.GetHotelInfoById({id:row.Id}).then(res=>{
							if(res.Success){
								this.colForm=res.Data;
								this.querylistbypid(this.colForm.ProvinceId,'CityList');
								this.querylistbypid(this.colForm.CityId,'AreaList');
								if(!this.colForm.HotelFacilitiesList.length){
									this.colForm.HotelFacilitiesList.push({
							      "FacilityType": "",
							      "FacilityValue": ""
							    })
								}
								if(!this.colForm.HotelSurroundFacilitiesList.length){
									this.colForm.HotelSurroundFacilitiesList.push({
										"FacilityType": "",
										"FacilityValue": ""
									})
								}
								this.checkHotelHits=this.colForm.HotelHints||[];
								this.$nextTick((val)=>{
			            this.roomColShow=true;
								})
							}
						})
          },
					deleteShow(title,row){
            this.$confirm(title, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
              center: true
            }).then(() => {
							this.TriggerHotelInfo(row);
            }).catch(() => {
            });
          },
          handleOnline(index, row) {
						this.deleteShow(row.IsOnLine?'确认下架！':'确认上架！',row)
          },
					handleOffline(index,row){
						this.deleteShow(row.IsOnLine?'确认下架！':'确认上架！',row)
					},
					TriggerHotelInfo({Id,IsOnLine}){
						let data={
							id:Id,
							isOnLine:!IsOnLine
						}
						this.$ajax.TriggerHotelInfo(data).then(res=>{
							if(res.Success){
								this.$message.success(IsOnLine?'已下架！':'已上架！');
								this.initList();
							}
						})
					},
					setIsMasterPhoto(m){
		        _.map(this.colForm.ImageList,val=>{
		          if(val.Name!==m.Name){
		            val.IsMasterPhoto=false;
		          }
		        })
		      },
					btnSave(formName){
						this.$refs[formName].validate((valid) => {
              if (valid) {
                this.$ajax.SaveBlocInfo(this.addData).then(res=>{
									if(res.Success){
										this.$message.success(this.dialogTitle+'成功!');
										this.$refs[formName].resetFields();
										this.initList();
									}
                })
              } else {
                return false;
              }
            });
					},
					saveColForm(formName){
						this.$refs[formName].validate((valid) => {
              if (valid) {
								this[formName].HotelHints=this.checkHotelHits;
                this.$ajax.SaveHotelInfo(this[formName]).then(res=>{
									if(res.Success){
										this.$message.success(this.dialogTitle+'成功!');
										this.$refs[formName].resetFields();
										this.initList();
									}
                })
              } else {
                return false;
              }
            });
					},
        }
	  }
</script>
